package com.xdf.utils;

import cn.hutool.core.codec.Base64;
import com.xdf.constant.CommonConstant;
import sun.misc.BASE64Decoder;
import java.io.IOException;
import java.security.*;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.HashMap;
import java.util.Map;

/**
 * @author chanchaw
 * @create 2025-08-21 16:29
 */
public class RSAUtils {
    public static Map<String,String> generateKeyBytes() throws NoSuchAlgorithmException {
        KeyPairGenerator rsa = KeyPairGenerator.getInstance("RSA");
        rsa.initialize(2048);// RSA要求最小2048长度
        KeyPair keyPair = rsa.generateKeyPair();
        RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
        RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();

        String publicKeyStr = Base64.encode(publicKey.getEncoded());
        String privateKeyStr = Base64.encode(privateKey.getEncoded());

        HashMap<String, String> ret = new HashMap<>();
        ret.put("publicKey",publicKeyStr);
        ret.put("privateKey",privateKeyStr);
        System.out.println("RSA生成的公钥、私钥依次是:\n" + publicKeyStr + "\n" + privateKeyStr);
        return ret;
    }

    // 从私钥字符串生成私钥对象
    public static PrivateKey getPrivateKey(String privateKeyStr) throws IOException, NoSuchAlgorithmException, InvalidKeySpecException {
        PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec(new BASE64Decoder().decodeBuffer(privateKeyStr));
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        return keyFactory.generatePrivate(priPKCS8);
    }

    public static PublicKey getPublicKey(String publicKeyStr) throws IOException, NoSuchAlgorithmException, InvalidKeySpecException {
        byte[] bytes = new BASE64Decoder().decodeBuffer(publicKeyStr);
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(bytes);
        return KeyFactory.getInstance("RSA").generatePublic(keySpec);
    }
}
